package com.cuit.riskassessment.action.cardinfo;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.cuit.riskassessment.service.CardInfoService;
import com.cuit.riskassessment.vo.CardInfo;
import com.cuit.riskassessment.vo.StaffInfo;

@Controller
@RequestMapping(value = "cardInfoAction")
public class CardInfoAction implements ServletContextAware {
	@Resource(name = "cardInfoServiceObject")
	private CardInfoService service;
	private ServletContext servletContext;

	@Override
	public void setServletContext(ServletContext arg0) {
		this.servletContext = arg0;
	}

	@RequestMapping(value = "addOrUpdate")
	public @ResponseBody
	Object addOrUpdate(CardInfo cardInfo) {
		Map<String, Object> res = new HashMap<String, Object>();
		if (cardInfo.getId() == null || cardInfo.getId().equals("")) {
			service.add(cardInfo);
			res.put("msg", "增加成功！");
		} else {
			service.update(cardInfo);
			res.put("msg", "修改成功！");
		}
		return res;
	}

	@RequestMapping(value = "del")
	public @ResponseBody
	Object del(String id) {
		Map<String, Object> res = new HashMap<String, Object>();
		service.del(id);
		res.put("msg", "删除成功");
		return res;
	}

	@RequestMapping(value = "getCards")
	public @ResponseBody
	Object getCards(@RequestParam("pid") String pid,
			@RequestParam("element") String element,
			@RequestParam("value") String value) {
		Map<String, Object> res = new HashMap<String, Object>();
		List<CardInfo> list = new ArrayList<CardInfo>();
		if (value == null || value.equals("")) {
			list = service.getAll(pid);
		} else if (element == null || element.equals("")) {
			list = service.getByElement(pid, "VC_NAME", value);
		} else {
			list = service.getByElement(pid, element, value);
		}
		for (int i = 0; i < list.size(); i++) {
			String name = list.get(i).getPhoto();
			if (name != null && !(name.equals(""))) {
				name = "<a target='_blank' href = " + "../upload/card/" + name
						+ ">点击查看</a>";
				list.get(i).setPhoto(name);
			}
		}
		res.put("list", list);
		return res;
	}

	@RequestMapping(value = "getNames")
	public @ResponseBody
	Object getNames(@RequestParam("value") String value)
			throws UnsupportedEncodingException {
		Map<String, Object> res = new HashMap<String, Object>();
		List<StaffInfo> list = new ArrayList<StaffInfo>();
		value = new String(value.getBytes("iso8859_1"), "utf-8");
		if (value == null || value.equals("")) {
			list = service.getAllName();
		} else {
			list = service.getNameByElement(value);
		}
		res.put("list", list);
		return res;
	}

	@RequestMapping(value = "delfile")
	public @ResponseBody
	String delFile(@RequestParam("fileName") String fileName) {
		String path = servletContext.getRealPath("/upload/card");
		File file = new File(path+"\\"+fileName);
		System.out.println(fileName);
		if (file.isFile() && file.exists()) {
			file.delete();
		}
		return "{success:true}";
	}

	@RequestMapping(value = "upload")
	public @ResponseBody
	String upload(@RequestParam("id") String id,
			@RequestParam("photo") String photo,
			@RequestParam("file") CommonsMultipartFile file) {
		if (file.getSize() >= 10000000) {
			return "{success:false,msg:'文件过大'}";
		}
		if (!file.isEmpty()) {
			String path = servletContext.getRealPath("/upload/card");
			File newfile = new File(path + "\\" + photo);
			try {
				file.getFileItem().write(newfile);
			} catch (Exception e) {
				e.printStackTrace();
				return "{success:false,msg:'文件上传失败！'}";
			}
		}
		return "{success:true}";
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "date")
	public @ResponseBody
	Object date() throws Exception {
		// 查全部证件
		List<CardInfo> cards = service.allCards();
		List<Object> list = new ArrayList<Object>();
		if (cards.size() > 0) {
			for (int i = 0; i < cards.size(); i++) {
				Calendar c = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
				// 获取办证日期
				Date usefulTime = sdf.parse(cards.get(i).getUsefulTime());
				// 获取最后一次检查时间
				Date usefulEndTime = sdf.parse(cards.get(i).getUsefulEndTime());
				// 获取周期
				Integer year = Integer
						.valueOf(cards.get(i).getYearUsefulTime());
				// 计算下一次检查时间
				String tempDate = (usefulEndTime.getYear() + year + 1900) + "/"
						+ (usefulTime.getMonth() + 1) + "/"
						+ usefulTime.getDate();
				System.out.println(c.getTime().getYear());
				Date nextTime = sdf.parse(tempDate);
				// 计算与下一次检查时间差
				long timeout = (nextTime.getTime() - new Date().getTime())
						/ (24 * 60 * 60 * 1000);
				if (timeout < 30) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("id", cards.get(i).getId());
					map.put("name", service.getName(cards.get(i).getPid()));
					map.put("cardName", cards.get(i).getName());
					map.put("usefulTime", cards.get(i).getUsefulTime());
					map.put("usefulEndTime", cards.get(i).getUsefulEndTime());
					if (timeout < 0) {
						map.put("time", "<font color=red>已超过" + (0 - timeout)
								+ "天</font>");
					} else {
						map.put("time", timeout + "天");
					}

					list.add(map);
				}
			}
		}
		return list;
	}

}
